//
//  LoginViewController.m
//  何五路
//
//  Created by _ADY on 15/6/25.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "ZCAndViewController.h"
#import "LoginViewController.h"

@interface ZCAndViewController ()

@end
static LoadingView *loading = nil;
@implementation ZCAndViewController
@synthesize countString,pString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"注册";
        self.view.backgroundColor = bgColor;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, 380) style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.scrollEnabled = NO;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    bgButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [bgButton setFrame:CGRectMake(20, mTableView.frame.size.height+mTableView.frame.origin.y+20, screenMySize.size.width-40, 40)];
    [bgButton setTitle:@"注册" forState:UIControlStateNormal];
    [bgButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgButton];
    [self PtButton];

}

-(void)aInBction:(id)sender
{
    //    int topType = ((UIButton*)sender).tag - 10;
}

-(void)loginAction
{
    if (mailField.text.length != 0)
    {
        [SendService alerViewMessage:mMailNull];
        return;
    }
    else if ([SendService validateEmail:mailField.text])
    {
        [SendService alerViewMessage:mMailNo];
        return;
    }
    
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    if (![password.text isEqualToString:aPassWord.text]) {
        [SendService alerViewMessage:mPass];
        return;
    }
    loading = [[LoadingView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loading];
    
    
    NSMutableDictionary *postDic2 = [[NSMutableDictionary alloc] init];
    [postDic2 setObject:account.text forKey:@"Username"];
    [postDic2 setObject:password.text forKey:@"Password"];
    [postDic2 setObject:aPassWord.text forKey:@"ConfirmPassword"];
    [postDic2 setObject:countString forKey:@"Phone"];
    if (mailField.text.length != 0) {
        [postDic2 setObject:@"" forKey:@"Email"];
    }
    else
    [postDic2 setObject:mailField.text forKey:@"Email"];
    if (pString.length != 0) {
        [postDic2 setObject:pString forKey:@"Referee"];
    }else
        [postDic2 setObject:@"" forKey:@"Referee"];
    NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];
    [postDic1 setObject:postDic2 forKey:@"model"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *myArray = [SendService CustomerRegister:postDic1];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"myArray %@",myArray);

            [loading closeLoading];
            
            if (![[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Result"]] isEqualToString:@"error"])
            {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }
            else
            {
                if (![[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Entity"]] isEqualToString:@"<null>"])
                {
                    NSString *dicString = nil;
                    for (NSDictionary *dic in [myArray objectForKey:@"Entity"])
                    {
                        if (dicString == nil) {
                            dicString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"value"]];
                        }
                        else
                          dicString = [NSString stringWithFormat:@"%@,%@",dicString,[dic objectForKey:@"value"]];
                    }
                    [SendService alerViewMessage:dicString];
                }

//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                [alert show];
            }
            
        });
    });
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isZCKey"];
    LoginViewController *browser = [[LoginViewController alloc] init];
    browser.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == 0)
        return 0.001;
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 1;
    return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
        return 142*screenMySize.size.width/320;
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        aTableView.showsVerticalScrollIndicator = NO;
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    cell.backgroundColor = [UIColor whiteColor];
    
    if (indexPath.section == 0)
        return [self mCell:cell aCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 1)
        return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    // Configure the cell...
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell aCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, screenMySize.size.width, 142*screenMySize.size.width/320)];
    [bgImageView setImage:[UIImage imageNamed:@"user_bg"]];
    [cell.contentView addSubview:bgImageView];
    
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *tArray = [NSArray arrayWithObjects:@"账号:",@"密码:",@"确认密码:",@"邮箱:",nil];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 95, 40)];
    titleLabel.text = [NSString stringWithFormat:@"%@",[tArray objectAtIndex:indexPath.row]];
    titleLabel.textAlignment = 2;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize+2];
    titleLabel.textColor = [UIColor blackColor];
    [cell.contentView addSubview:titleLabel];
    
//    cell.textLabel.text = [tArray objectAtIndex:indexPath.row];
//    cell.textLabel.textAlignment = 2;
//    cell.textLabel.textColor = [UIColor blackColor];
    
    if (indexPath.row == 1)
    {
        password = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, screenMySize.size.width-110, 40)];
        password.backgroundColor = [UIColor clearColor];
        [password setFont:[UIFont systemFontOfSize:labelSize]];
        password.returnKeyType = UIReturnKeyGo;
        [password setPlaceholder:@"请输入密码"];
        [password setClearButtonMode:UITextFieldViewModeWhileEditing];
        password.delegate = self;
        password.secureTextEntry = YES;
        //        password.text = @"123";
        [cell.contentView addSubview:password];

    }
    else if (indexPath.row == 0)
    {
        account = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, screenMySize.size.width-110, 40)];
        account.backgroundColor = [UIColor clearColor];
        [account setFont:[UIFont systemFontOfSize:labelSize]];
        account.returnKeyType = UIReturnKeyNext;
        [account setClearButtonMode:UITextFieldViewModeWhileEditing];
        account.delegate = self;
        [account setPlaceholder:@"请输入账号"];
        [cell.contentView addSubview:account];
        
    }
    else if (indexPath.row == 2)
    {
        aPassWord = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, screenMySize.size.width-110, 40)];
        aPassWord.backgroundColor = [UIColor clearColor];
        [aPassWord setFont:[UIFont systemFontOfSize:labelSize]];
        aPassWord.returnKeyType = UIReturnKeyNext;
        [aPassWord setClearButtonMode:UITextFieldViewModeWhileEditing];
        aPassWord.delegate = self;
        aPassWord.secureTextEntry = YES;
        //        account.text = @"admin@hewulu.com";
        [aPassWord setPlaceholder:@"请确认密码"];
        [cell.contentView addSubview:aPassWord];
        
    }
    else if (indexPath.row == 3)
    {
        mailField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, screenMySize.size.width-110, 40)];
        mailField.backgroundColor = [UIColor clearColor];
        [mailField setFont:[UIFont systemFontOfSize:labelSize]];
        mailField.returnKeyType = UIReturnKeyNext;
        [mailField setClearButtonMode:UITextFieldViewModeWhileEditing];
        mailField.delegate = self;
        //        account.text = @"admin@hewulu.com";
        [mailField setPlaceholder:@"请输入邮箱"];
        [cell.contentView addSubview:mailField];
        
    }
    
    [self PtButton];
    
    return cell;
}


#pragma mark -
#pragma mark UITextFieldDelegate
//限制输入长度 by zwb 2011.9.6
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == password ||textField == aPassWord ) {
        if (range.location > 15){
            
            [SendService alerViewMessage:mPasswordLong];
            textField.text = [textField.text substringToIndex:[textField.text length] - 1];
            return NO;
        }
        
    }
    
    [self PtButton];
    return YES;
    
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    [mTableView setContentOffset:CGPointMake(0, 90) animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == account) {
        [password becomeFirstResponder];
    }
    else if (textField == password) {
        [aPassWord becomeFirstResponder];
    }
    else if (textField == aPassWord) {
        [mailField becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
        [mTableView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
    [self PtButton];
    
    return YES;
}

-(void)PtButton
{
    if (account.text.length!=0 &&password.text.length!=0 &&aPassWord.text.length!=0)
    {
        [bgButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        bgButton.enabled = YES;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButtons"] forState:UIControlStateNormal];
    }
    else
    {
        [bgButton setTitleColor:[UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1] forState:UIControlStateNormal];
        bgButton.enabled = NO;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButton"] forState:UIControlStateNormal];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
